<template>
  <div class="execution-history-overview-wrap">
    <div class="grid-column-4">
      <icon-kpi :config="kpi_1"></icon-kpi>
      <icon-kpi :config="kpi_2"></icon-kpi>
      <icon-kpi :config="kpi_3"></icon-kpi>
      <icon-kpi :config="kpi_4"></icon-kpi>
    </div>

    <div class="column-divided"></div>
    <div class="grid-column-1">
      <div class="chart-container relationship-chart">
        <div class="topChart">
          <div class="formDiv">
            <span class="label">数据库类型</span>
            <el-select
              v-model="queryParams.dbType"
              placeholder="请选择"
              @change="commonChange"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in dbTypeList"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <!--            <el-form :model="queryParams" label-width="100px" :inline="true" class="formStyle" @submit.native.prevent>-->
            <!--                <el-col :span="12">-->
            <!--                  <el-form-item label="数据库类型" prop="dbType">-->
            <!--                    <el-select v-model="queryParams.dbType" placeholder="请选择" @change="commonChange" clearable>-->
            <!--                      <el-option-->
            <!--                        v-for="(item,index) in dbTypeList"-->
            <!--                        :key="index"-->
            <!--                        :label="item"-->
            <!--                        :value="item"-->
            <!--                      >-->
            <!--                      </el-option>-->
            <!--                    </el-select>-->
            <!--                  </el-form-item>-->
            <!--                </el-col>-->
            <!--                <el-col :span="12">-->
            <!--                  <el-form-item label="客户端IP" prop="sourceIp">-->
            <!--                    <el-select v-model="queryParams.sourceIp" placeholder="请选择" filterable @change="commonChange"-->
            <!--                               clearable>-->
            <!--                      <el-option-->
            <!--                        v-for="(item,index) in sourceIpList"-->
            <!--                        :key="index"-->
            <!--                        :label="item"-->
            <!--                        :value="item"-->
            <!--                      ></el-option>-->
            <!--                    </el-select>-->
            <!--                  </el-form-item>-->
            <!--                </el-col>-->
            <!--            </el-form>-->
          </div>
          <div class="formDiv">
            <span class="label">客户端IP</span>
            <el-select
              v-model="queryParams.sourceIp"
              placeholder="请选择"
              filterable
              @change="commonChange"
              clearable
            >
              <el-option
                v-for="(item, index) in sourceIpList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <!--        <title-chart-->
        <!--          type="chart-relation"-->
        <!--          title="已扫描敏感表类别分布"-->
        <!--          :dataset="relationDataSet"-->
        <!--        ></title-chart>-->
        <div class="EChart-container">
          <CommonMagnifierView>
            <RelationCanvas
              :type="queryParams.dbType"
              :option="columnOption1"
            ></RelationCanvas>
          </CommonMagnifierView>
        </div>
        <!--        <base-chart-->
        <!--          slot="content"-->
        <!--          :option="columnOption1"-->
        <!--        >-->
        <!--        </base-chart>-->
      </div>
    </div>
    <div class="column-divided"></div>
    <div class="grid-column-1">
      <div class="chart-container">
        <title-card title="实时统计">
          <base-chart
            :option="realTimeQueue"
            v-if="realTimeQueue.dataset.source.length"
          ></base-chart>
          <div class="chart-tooltip" v-else>
            <commonIcon
              iconName="icon-wushuju"
              iconType="icon"
              :iconSize="36"
            ></commonIcon>
            <span class="tip-content">暂无数据</span>
          </div>
        </title-card>
      </div>
    </div>
    <div class="column-divided"></div>
    <div class="grid-column-2">
      <div class="chart-container">
        <title-chart
          type="chart-cirque"
          title="数据分级分布"
          :dataset="pieLeftDataSet"
        ></title-chart>
      </div>
      <div class="chart-container">
        <title-chart
          type="chart-cirque"
          title="敏感等级分布"
          :dataset="pieRightDataSet"
        ></title-chart>
      </div>
    </div>

    <div class="column-divided"></div>
    <div class="grid-column-2">
      <div class="chart-container">
        <title-chart
          type="chart-column"
          title="敏感字段Top10"
          :dataset="columnLeftDataSet"
        ></title-chart>
      </div>
      <div class="chart-container">
        <title-chart
          type="chart-column"
          title="客户端IP Top10"
          :dataset="columnRightDataSet"
        ></title-chart>
      </div>
    </div>
    <div class="column-divided"></div>
    <div class="grid-column-2">
      <div class="chart-container">
        <title-chart
          type="chart-bar"
          title="数据源(库)"
          :dataset="barLeftDataSet"
        ></title-chart>
      </div>
      <div class="chart-container">
        <title-chart
          type="chart-bar"
          title="数据源(表)"
          :dataset="barRightDataSet"
        ></title-chart>
      </div>
    </div>
  </div>
</template>

<script>
import IconKpi from "@/components/IconKpi";
import TitleChart from "@/components/EChart/TitleChart";
import {
  getGraphData,
  getSpreadOverview,
  getSpreadRinkingReportKpi,
  spreadCatatoryList, //下拉列表
  totalDiffusion, //已扫描敏感表类别分布图
  queryRealTimeQueue,
} from "@/api/overview/spread";
import BaseChart from "@/components/EChart/components/BaseChart";
import BaseList from "@/mixins/BaseList";
import CommonMagnifierView from "@/components/CommonMagnifierView";
import RelationCanvas from "@/components/EChart/canvas/relation";
import CommonIcon from "@/components/CommonIcon";
import { getPercent } from "@/utils/util";
export default {
  name: "overviewIndex",
  mixins: [BaseList],

  data() {
    return {
      dbTypeList: [],
      sourceIpList: [],
      queryParams: {
        dbType: null,
        sourceIp: null,
      },
      flag: false,
      kpi_1: {
        icon: "iconfont icon-database",
        color: "#e69138",
        label: "扩散数据库总数",
        value: 0,
      },
      kpi_2: {
        icon: "iconfont icon-chart",
        color: "#72c140",
        label: "扩散表总数",
        value: 0,
      },
      kpi_3: {
        icon: "iconfont icon-minganbiaoziduanzongshu",
        color: "#e13c39",
        label: "扩散敏感字段总数",
        value: "0",
      },
      kpi_4: {
        icon: "iconfont icon-kehuduan",
        color: "#448ef7",
        label: "扩散客户端总数",
        value: "0",
      },

      pieLeftDataSet: {
        dimensions: ["typeName", "spreadCount"],
        source: [],
        option: {
          legend: {
            formatter: function (name) {
              return name + " | ";
            },
          },
          tooltip: {
            show: true,
            position: function (point, params, dom, rect, size) {
              return [0, point[1]];
            },
            formatter: function (params) {
              return `<div>${params.marker} ${params.name} | ${
                params.percent ? params.percent : 0
              }%  ${params.data["spreadCount"]}</div>`;
            },
          },
        },
      }, // 数据分级
      pieRightDataSet: {
        dimensions: ["sensitiveLevelName", "spreadCount"],
        source: [],
        option: {
          legend: {
            formatter: function (name) {
              return name + " | ";
            },
          },
          tooltip: {
            show: true,
            position: function (point, params, dom, rect, size) {
              return [0, point[1]];
            },
            formatter: function (params) {
              return `<div>${params.marker} ${params.name} | ${
                params.percent ? params.percent : 0
              }%  ${params.data["spreadCount"]}</div>`;
            },
          },
        },
      }, // 敏感等级

      columnLeftDataSet: {
        dimensions: ["sensitiveWord", "spreadCount"],
        source: [],
        option: {
          color: ["#e69137"],
        },
      }, // 敏感字段
      columnRightDataSet: {
        dimensions: ["sourceIp", "spreadCount"],
        source: [],
        option: {
          color: ["#4ab237"],
        },
      }, // 客户端
      realTimeQueue: {
        color: ["#72C141", "#D9211F"],
        tooltip: {
          show: true,
        },
        legend: {
          show: true,
          orient: "horizontal",
          itemWidth: 22,
          itemHeight: 10,
          lineStyle: {
            type: "solid",
          },
        },
        grid: {
          right: 10,
          bottom: 50,
          top: 40,
        },
        dataset: {
          // 用 dimensions 指定了维度的顺序。直角坐标系中，
          // 默认把第一个维度映射到 X 轴上，第二个维度映射到 Y 轴上。
          // 如果不指定 dimensions，也可以通过指定 series.encode
          dimensions: ["lable", "JS4123SJ", "JS4324ASJ"],
          source: [],
        },
        xAxis: {
          show: true,
          type: "category",
          axisLine: {
            show: true,
          }, // 坐标轴线
          axisTick: {
            show: false,
          }, // 坐标轴刻度
          axisLabel: {
            rotate: -15,
            align: "center",
            margin: 20,
            interval: 0,
            show: true,
            width: 68,
          }, // 坐标轴标签
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          name: "单位： 次",
          nameGap: 22,
          type: "value",
          axisLine: {
            show: true,
          },
          axisTick: {
            show: false,
          }, // 坐标轴刻度
          axisLabel: {
            show: true,
          }, // 坐标轴标签
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
            },
          },
        },
        series: [
          {
            type: "line",
            symbol: "circle",
            lineStyle: {
              width: 1,
              type: "dashed",
            },
          },
          {
            type: "line",
            symbol: "circle",
            lineStyle: {
              width: 1,
              type: "dashed",
            },
          },
        ],
      },
      barLeftDataSet: {
        dimensions: ["dbName", "spreadCount"],
        source: [],
        option: {
          color: ["#d50202"],
        },
      }, // 数据源(库)
      barRightDataSet: {
        dimensions: ["tableName", "spreadCount"],
        source: [],
        option: {
          color: ["#e2bb22"],
        },
      }, // 数据源(表)

      // relationDataSet: {
      //   dimensions: [],
      //   source: [],
      //   common: {
      //     nodes: [],
      //     links: [],
      //     categories: []
      //   }
      // },// 关系图
      columnOption1: [],

      minganTotle: 0,
      mingan2Totle: 0,
      minganTotleCount: 0,
    };
  },
  components: {
    BaseChart,
    IconKpi,
    TitleChart,
    CommonMagnifierView,
    RelationCanvas,
    CommonIcon,
  },
  created() {
    // this.getGraphData()

    this.getSensitiveLevel(); // 敏感等级
    this.getDataLevel(); // 数据分级
    this.getDataBase(); // 数据库
    this.getDataTable(); // 数据表
    this.getSensitiveWord(); //敏感字段
    this.getSourceIp(); // 客户端IP
    this.getKpi1(); // kpi
    this.getKpi2(); // kpi
    this.getKpi3(); // kpi
    this.getKpi4(); // kpi
    this.homeDownIp(); //客户端IP下拉列表
    this.homeDownType(); //数据库类型下拉列表
    this.getRealTimeQueue();
  },
  methods: {
    //实时统计
    getRealTimeQueue() {
      queryRealTimeQueue().then((res) => {
        if (res && res.code === 200) {
          let arrVal = Object.entries(res.data);
          let dateList = [];
          let numname = ["lable"];
          arrVal.map((item) => {
            numname.push(...Object.keys(item[1]));
            dateList.push({
              ...item[1],
              lable: item[0],
            });
          });
          this.realTimeQueue.dataset.dimensions = [...new Set(numname)];
          this.realTimeQueue.series = [];
          this.realTimeQueue.dataset.dimensions.map((item, index) => {
            this.realTimeQueue.series.push({
              type: "line",
              symbol: "circle",
              lineStyle: {
                width: 1,
                type: "dashed",
              },
            });
          });
          this.realTimeQueue.dataset.source = dateList;
        }
      });
    },
    //数据库类型下拉列表
    homeDownType() {
      spreadCatatoryList({
        sensitiveFlag: 0,
        statNames: "dbType",
      }).then((res) => {
        if (res && res.code === 200) {
          this.dbTypeList = res.data;
          //在接口返回之后，有数据的情况下调扩散总数图的接口
          if (this.dbTypeList.length) {
            this.queryParams.dbType = this.dbTypeList[0];
            this.commonChange();
          }
        } else {
          this.dbTypeList = [];
        }
      });
    },
    commonChange() {
      let params = {};
      if (this.queryParams.dbType) params.dbType = this.queryParams.dbType;
      if (this.queryParams.sourceIp)
        params.sourceIp = this.queryParams.sourceIp;

      if (params.dbType) {
        this.getDiffusionData(params);
      } else {
        // 未选择数据库类型
      }
    },
    //客户端IP 下拉框
    homeDownIp() {
      const params = {
        sensitiveFlag: 0,
        statNames: "sourceIp",
      };
      spreadCatatoryList(params).then((res) => {
        if (res && res.code === 200) {
          this.sourceIpList = res.data;
        } else {
          this.sourceIpList = [];
        }
      });
    },
    /**
     * 扩散图
     */
    // getDiffusionData(params) {
    //   totalDiffusion(params).then(res => {
    //     if (res && res.code === 200) {
    //       let { nodes, links, categories } = res.data
    //       this.relationDataSet.common.nodes = nodes.reduce((r, c) => {
    //         r.push({
    //           ...c,
    //           x: undefined,
    //           y: undefined
    //         })
    //         return r
    //       }, [])
    //       this.relationDataSet.common.links = links
    //       this.relationDataSet.common.categories = categories
    //       this.relationDataSet.source = this.relationDataSet.common.nodes
    //     } else {
    //
    //     }
    //   }).catch(err => {
    //
    //   })
    // },
    getDiffusionData(params) {
      totalDiffusion(params).then((res) => {
        if (res && res.code === 200) {
          this.columnOption1 = res.data.reduce((r, c) => {
            r.push({
              ...c,
              name: `${c.dbIp + c.dbName}`,
              num: c.spreadCount,
            });
            return r;
          }, []);
          // this.columnOption1.series[0].links = res.data.links
          // this.columnOption1.series[0].categories = res.data.categories
          // this.columnOption1.legend.data = res.data.categories.filter(item => item.name !== 'sourceIp')
        } else {
          this.columnOption1 = [];
        }
      });
    },
    // getGraphData(params) {
    //   getGraphData(params).then(res => {
    //     if (res && res.code === 200) {
    //       let { nodes, links, categories } = res.data
    //
    //       this.relationDataSet.common.nodes = nodes.reduce((r, c) => {
    //         r.push({
    //           ...c,
    //           x: undefined,
    //           y: undefined
    //         })
    //         return r
    //       }, [])
    //       this.relationDataSet.common.links = links
    //       this.relationDataSet.common.categories = categories
    //       this.relationDataSet.source = this.relationDataSet.common.nodes
    //     } else {
    //
    //     }
    //   }).catch(err => {
    //
    //   })
    // },
    /**
     * 数据分级
     */
    getDataLevel() {
      this.getSpreadOverview("sensitiveTypes.typeName").then((res) => {
        if (!res.every((item) => item.spreadCount == 0)) {
          this.pieLeftDataSet.source = res;
          let _this = this;
          this.pieLeftDataSet.option.legend.formatter = function (name) {
            let pieLeftDataSet = "";
            let pieLeftCount = 0;
            let dbLeTypeCount = "";
            _this.pieLeftDataSet.source.forEach((item) => {
              pieLeftCount = pieLeftCount + item.spreadCount;
              if (item.typeName == name) {
                pieLeftDataSet = item.typeName + " | ";
                dbLeTypeCount = " " + item.spreadCount;
              }
            });
            pieLeftDataSet =
              pieLeftDataSet +
              _this.getPercent(dbLeTypeCount, pieLeftCount) +
              dbLeTypeCount;
            return pieLeftDataSet;
          };
        }
      });
    },

    /**
     * 敏感等级
     */
    getSensitiveLevel() {
      this.getSpreadOverview("sensitiveLevelName").then((res) => {
        if (!res.every((item) => item.spreadCount == 0)) {
          this.pieRightDataSet.source = res;
          let _this = this;
          this.pieRightDataSet.option.legend.formatter = function (name) {
            let pieRightDataSet = "";
            let pieLeftCount = 0;
            let dbLeTypeCount = "";
            _this.pieRightDataSet.source.forEach((item) => {
              pieLeftCount = pieLeftCount + item.spreadCount;
              if (item.sensitiveLevelName == name) {
                pieRightDataSet = item.sensitiveLevelName + " | ";
                dbLeTypeCount = " " + item.spreadCount;
              }
            });
            pieRightDataSet =
              pieRightDataSet +
              getPercent(dbLeTypeCount, pieLeftCount) +
              dbLeTypeCount;
            return pieRightDataSet;
          };
        }
      });
    },

    /**
     * 数据源 库
     */
    getDataBase() {
      this.getSpreadOverview("dbIp,dbPort,dbName").then((res) => {
        this.barLeftDataSet.source = res;
      });
    },

    /**
     * 数据源 表
     */
    getDataTable() {
      this.getSpreadOverview("dbIp,dbPort,dbName,tableName").then((res) => {
        this.barRightDataSet.source = res;
      });
    },

    /**
     * 敏感字段
     */
    getSensitiveWord() {
      this.getSpreadOverview("sensitiveWord").then((res) => {
        this.columnLeftDataSet.source = res;
      });
    },
    /**
     * 客户端 IP
     */
    getSourceIp() {
      this.getSpreadOverview("sourceIp").then((res) => {
        this.columnRightDataSet.source = res;
      });
    },

    /**
     * 通用请求
     * @param statNames
     * @returns {Promise<unknown>}
     */
    getSpreadOverview(statNames) {
      return new Promise((resolve, reject) => {
        getSpreadOverview({
          statNames,
          sensitiveFlag: 0,
          topCount: 10,
        }).then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          } else {
            if (!this.flag) {
              this.handleListTips(res);
              this.flag = true;
            }
          }
        });
      });
    },

    getKpi1() {
      this.getKPIData("dbIp,dbPort,dbName").then((res) => {
        this.kpi_1.value = res;
      });
    },
    getKpi2() {
      this.getKPIData("dbIp,dbPort,dbName,tableName").then((res) => {
        this.kpi_2.value = res;
      });
    },
    getKpi3() {
      this.getKPIData("sensitiveWord").then((res) => {
        this.kpi_3.value = res;
      });
    },
    getKpi4() {
      this.getKPIData("sourceIp").then((res) => {
        this.kpi_4.value = res;
      });
    },

    getKPIData(statNames) {
      return new Promise((resolve, reject) => {
        getSpreadRinkingReportKpi({
          sensitiveFlag: 0,
          statNames,
        })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res.data);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.execution-history-overview-wrap {
  width: 100%;
  height: 100%;
  overflow-y: scroll;

  .chart-container {
    width: 100%;
    height: 400px;
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.1) 0 2px 12px 0;
    border-radius: 4px;

    .topChart {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      .formDiv {
        width: 300px;
        display: flex;
        align-items: center;
        z-index: 99;
        margin: 0 16px;

        .label {
          width: 80px;
          display: block;
          margin-right: 6px;
          font-size: 14px;
          color: #606266;
          text-align: right;
        }

        .el-select {
          width: calc(100% - 86px);
        }
      }
    }

    .EChart-container {
      width: 100%;
      height: calc(100% - 52px);
    }
  }

  .relationship-chart {
    height: 700px;
    width: 100%;
    padding-top: 20px;
    box-sizing: border-box;
  }

  .grid-column-5 {
    display: grid;
    grid-column-gap: 12px;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  }

  .grid-column-4 {
    display: grid;
    grid-column-gap: 12px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
  }

  .grid-column-2 {
    display: grid;
    grid-column-gap: 12px;
    grid-template-columns: 1fr 1fr;
  }

  .grid-column-1 {
    display: grid;
    grid-column-gap: 12px;
    //grid-template-columns: 1fr;
    grid-template-columns: minmax(0, 1fr);
    //overflow: hidden
  }

  .column-divided {
    height: 12px;
    width: 100%;
  }

  .EChart-container {
  }
}
.chart-tooltip {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0.5;

  .icon-wushuju {
    font-size: 36px;
  }

  .tip-content {
    font-size: 12px;
  }
}
</style>
